<template>

	<view class="">
		<view v-for="(item, i) in goodsList" :key="i" @click="gotoGoodsDetail(item)">
			<my-goods :item="item"></my-goods>
		</view>
	</view>


</template>

<script>

import { getGoods } from '@/config/api.js';
	export default {
		data() {
			return {
				queryInfo:{
					query: '',
					cid: '',
					pagenum: 1,
					pagesize: 10,
				},
				goodsList: [],
				total: 0,
				isLoading: false,
				timer: null,
				loadingText: '加载更多'
			};
		},
		onLoad(options){
			
			this.queryInfo.query = options.query || ''
			this.queryInfo.cid = options.cid || ''
			console.log(this.queryInfo);
			this.getGoodsList()
		},
		//下拉刷新
		onPullDownRefresh() {
			//下拉的生命周期
			
			this.queryInfo.pagenum = 1,
			this.total = 0,
			this.isLoading = false,
			this.goodsList = [],
			
			// 重新发起请求 cb回调函数
			this.getGoodsList(() => uni.stopPullDownRefresh())
		},
		//上拉加载
		onReachBottom() {
			
			//阻止重复加载
			if (this.isLoading) return  //节流
			
			this.queryInfo.pagenum++
			this.getMoreGoodsList()
		},
		methods:{
			async getGoodsList(cb){
				this.isLoading = true
				const {data:res} = await getGoods(this.queryInfo)
				this.isLoading = false
				
				// 只要数据请求完毕，就立即按需调用 cb 回调函数
				// 检查cb存在与否，存在执行，这样写的目的是为了防止错误，如果定义了cb，这个时候写cb()也是可以的
				// 短路运算符，
				cb && cb()
			    this.goodsList = [...this.goodsList,...res.message.goods]
				this.total = res.message.total
			
				console.log(res);
			},
			getMoreGoodsList(){
				this.loadingText = '加载中'
				this.$u.toast(this.loadingText)
				uni.showNavigationBarLoading()  //加载动画
				if(this.queryInfo.pagenum * this.queryInfo.pagesize < this.total){
					this.getGoodsList()
					
					//停止下拉样式
					
					//隐藏标题读取
					uni.hideNavigationBarLoading()
				}else {
					this.loadingText = "已经加载全部"
					this.$u.toast(this.loadingText)
				}
			},
			gotoGoodsDetail(item){
				uni.navigateTo({
					url:'../goods_detail/goods_detail?goods_id='+item.goods_id
				})
			}
		}
	}
</script>

<style lang="scss">
	
</style>